package com.wuax.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.wuax.domain.Book;
import com.wuax.domain.vo.LayTableData;
import com.wuax.domain.vo.Result;
import com.wuax.mapper.BookMapper;
import com.wuax.service.BookService;
import com.wuax.utils.BookCodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookMapper bookMapper;

    @Override
    public LayTableData list(Book book) {
        // 只查询未删除的
        book.setIsDelete("0");
        // 查询总条数
        int i = bookMapper.selectCount(book);
        // 获取图书数据并返回laytable需求的格式
        return new LayTableData(i, bookMapper.select(book));
    }

    @Override
    public Result add(Book book) {
        // 生成uuid
        book.setBookId(IdUtil.simpleUUID());
        
        // 生成规范的图书编码
        String bookNumber = generateBookNumber(book.getBookTypeId());
        if (StrUtil.isBlank(bookNumber)) {
            return Result.error("分类信息不存在，无法生成图书编码");
        }
        book.setBookNumber(bookNumber);
        
        // 初始化参数，未借出和未删除
        book.setBorrowId(null);
        book.setIsDelete("0");
        // 添加到数据库
        int insert = bookMapper.insert(book);
        return insert == 1 ? Result.success("入库成功") : Result.error("入库失败");
    }
    
    /**
     * 生成图书编码
     * @param bookTypeId 图书分类ID
     * @return 图书编码
     */
    private String generateBookNumber(String bookTypeId) {
        if (StrUtil.isBlank(bookTypeId)) {
            return null;
        }
        
        // 获取分类编码
        String bookTypeCode = bookMapper.selectBookTypeCodeById(bookTypeId);
        if (StrUtil.isBlank(bookTypeCode)) {
            return null;
        }
        
        // 获取当前年月
        String currentYearMonth = BookCodeGenerator.getCurrentYearMonth();
        
        // 查询该分类当月已有图书数量
        int existCount = bookMapper.selectCountByTypeIdAndYearMonth(bookTypeId, currentYearMonth);
        
        // 生成序号（从1开始）
        int sequenceNumber = existCount + 1;
        
        // 生成图书编码
        return BookCodeGenerator.generateBookCode(bookTypeCode, sequenceNumber);
    }

    @Override
    public Result update(Book book) {
        // 不更新创建时间
        book.setCreateDate(null);
        return bookMapper.update(book) == 1 ? Result.success("修改成功") : Result.error("修改失败");
    }

    @Override
    public Result batchDelete(List<String> bookIds) {
        // 批量删除
        return bookMapper.batchDelete(bookIds) > 0 ? Result.success("删除成功") : Result.error("删除失败");
    }
}
